package com.tensquare.friend.interceptor;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * JWT验证 拦截器
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 在方法执行之前执行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // System.out.println("经过了拦截器");

        /*
        无论如何都放行，具体能不能操作还是在具体的操作中去判断
        拦截器只是负责把头请求中包含Token的令牌进行一个解析验证
         */
        // 获取请求头
        String header = request.getHeader("Authorization");

        if (null != header && !"".equals(header.trim())) {
            // 包含头信息，对其进行解析

            // 是否以“Bearer ”开头
            if (header.startsWith("Bearer ")) {
                // 获取Token
                String token = header.substring(7);

                // 解析Token出错会报异常
                try {
                    Claims claims = jwtUtil.parseJWT(token);
                    // 获取用户角色
                    String roles = (String) claims.get("roles");

                    if (null != roles && "admin".equals(roles)) {
                        request.setAttribute("claims_admin", claims);
                    } else if (null != roles && "user".equals(roles)) {
                        request.setAttribute("claims_user", claims);
                    }

                } catch (Exception e) {
                    throw new RuntimeException("令牌有误");
                }
            }

        }

        return true;
    }


}
